package com.servertest1;

import java.io.UnsupportedEncodingException;

import java.security.NoSuchAlgorithmException;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

public class MainFragment extends Fragment implements OnClickListener {
	private static final String TAG = "MainFragment";
	private UiLifecycleHelper uiHelper;
	private Client client;
	String username = "user";
	String password = "password";
	Button btnLogin, btnCancel, btnNewUser;
	private EditText usr;
	private EditText pswrd;
	private DatabaseHelper checker;

	private Session.StatusCallback callback = new Session.StatusCallback() {
		// @Override //(Move on for now, part of step 2 for FB login)
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
		client = new Client();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		

		View view = inflater.inflate(R.layout.login, container, false);
		/*LoginButton authButton = (LoginButton) view
				.findViewById(R.id.authButton);
		authButton.setFragment(this);*/
		
		btnLogin = (Button) view.findViewById(R.id.btnLogin);
		btnCancel = (Button) view.findViewById(R.id.btnCancel);
		btnNewUser = (Button) view.findViewById(R.id.btnNewUser);

		// Link text fields to variables
		usr = (EditText) view.findViewById(R.id.username);
		pswrd = (EditText) view.findViewById(R.id.password);

		// Set click listener
		btnLogin.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		btnNewUser.setOnClickListener(this);
		
		

		return view;
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (state.isOpened()) {
			Log.i(TAG, "Logged in...");
			//newFacebookUser();
			//Intent intent = new Intent(getActivity(), Menu.class);
			//startActivity(intent);
			//getActivity().finish();
		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
		}
	}

	private void newFacebookUser() {
		
		final Session session = Session.getActiveSession();
		Request request = Request.newMeRequest(session,
				new Request.GraphUserCallback() {
					public void onCompleted(GraphUser user, Response response) {
						// If the response is successful
						if (session == Session.getActiveSession()) {
							if (user != null) {
								username = "testing";
								password = "testing";
							}
						}
						if (response.getError() != null) {
							// Handle errors, will do so later.
						}
						
						try {
							password = SHA1.SHA1encrypt(password);
						} catch (NoSuchAlgorithmException e1) {
							e1.printStackTrace();
						} catch (UnsupportedEncodingException e1) {
							e1.printStackTrace();
						}

						// Attempt to create new account
						String[] cmd = new String[3];
						cmd[0] = "newUser";
						cmd[1] = username;
						cmd[2] = password;

						new CreateAccountTask().execute(cmd);
						
					}
				});
		request.executeAsync();
	}

	private class CreateAccountTask extends AsyncTask<String, Void, String[]> {

		protected String[] doInBackground(String... cmd) {
			client.connect();
			client.sendData(cmd);
			String result[] = client.recieveData();
			client.close();

			return result;
		}

		protected void onPostExecute(String[] result) {
			if (result[0].equals("added")) {
				Intent intent = new Intent(getActivity(), Menu.class);
				startActivity(intent);
				getActivity().finish();
			} else if (result[0].equals("user_already_in_database")) {
				try {

					password = SHA1.SHA1encrypt(password);
					String[] cmd = new String[3];
					cmd[0] = "login";
					cmd[1] = username;
					cmd[2] = password;

				} catch (Exception e) {
					//Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
				}
			} else {
				Toast.makeText(getActivity(),
						"Database returned something wierd: " + result[0],
						Toast.LENGTH_LONG).show();
			}
		}
	}

	public class loginTask extends AsyncTask<String, Void, String[]>{
		protected String[] doInBackground(String... cmd){

			client.connect();
			System.out.println("after");
			client.sendData(cmd);
			String[] result = client.recieveData();
			client.close();

			return result;

		}

		protected void onPostExecute(String[] result){


			if(result[0].equals("success")){
				Intent myIntent = new Intent(getActivity(), Menu.class);
				myIntent.putExtra("gameData", result);
				checker = new DatabaseHelper(getActivity());
				checker.insert(MainFragment.this.usr.getText().toString());
				startActivity(myIntent);
				getActivity().finish();
			}
			else if(result[0].equals("auto_success")){
				Intent myIntent = new Intent(getActivity(), Menu.class);
				myIntent.putExtra("gameData", result);
				startActivity(myIntent);
				getActivity().finish();
			}
			else if(result[0].equals("account_does_not_exist")){
				Toast.makeText(getActivity(), "This account does not exist", Toast.LENGTH_LONG).show(); 
			}
			else if(result[0].equals("account_does_not_exist_auto_login")){
				checker = new DatabaseHelper(getActivity());
				checker.deleteAll();
				Intent myIntent = new Intent(getActivity(), Login.class);
				startActivity(myIntent);
				getActivity().finish();
			}
			else if(result[0].equals("incorrect_password")){
				Toast.makeText(getActivity(), "The username and password do not match.", Toast.LENGTH_LONG).show();
			}
			else{
				Toast.makeText(getActivity(), "An unexpected error has occured.", Toast.LENGTH_LONG).show();
			}
		}		
	}
	
	@Override
	public void onResume() {
		super.onResume();

		// For scenarios where the main activity is launched and user
		// session is not null, the session state change notification
		// may not be triggered. Trigger it if it's open/closed.
		Session session = Session.getActiveSession();
		if (session != null && (session.isOpened() || session.isClosed())) {
			onSessionStateChange(session, session.getState(), null);
		}

		uiHelper.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	public void onClick(View v) {
		switch (v.getId()){
		case R.id.btnLogin:
			login();
			break;
		case R.id.btnCancel:
			getActivity().finish();
			break;
		case R.id.btnNewUser:
			System.out.println("IN THE NEW USER FRAGMENT!!");
			Intent myIntent = new Intent(getActivity(), Account.class);
			startActivity(myIntent);
			break;
		default:
			break;
		}
		
	}
	
	public void login()
	{
		username = usr.getText().toString();
		password = pswrd.getText().toString();

		if(!((usefulMethods.isAllNumberOrAlpha(username) && usefulMethods.isAllNumberOrAlpha(password)))){
			Toast.makeText(getActivity(), "Invalid username or password", Toast.LENGTH_LONG).show();
			return;
		}

		if(username.length() < 5 || username.length() > 15 || password.length() < 5 || password.length() > 15){
			Toast.makeText(getActivity(), "Invalid username or password.", Toast.LENGTH_LONG).show();
			return;
		}

		try {

			password = SHA1.SHA1encrypt(password);
			String[] cmd = new String[3];
			cmd[0] = "login";
			cmd[1] = username;
			cmd[2] = password;

			new loginTask().execute(cmd);

		} catch (Exception e) {
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		}

	}

}
